// JavaScript Document
_dss_editor._operation = {};
_dss_editor._operation.fire = function(eventObj) {
	try {
		switch (eventObj.eventType) {
			case MOUSE_L_DOWN:
			case MOUSE_R_DOWN:
				this.handleMouseDown(eventObj);
				break;
			case MOUSE_UP:
				this.handleMouseUp(eventObj);
				break;
			case MOUSE_MOVE:
				this.handleMouseMove(eventObj);
				break;
			case MOUSE_DBCLICK:
				this.handleMouseDBClick(eventObj);
				break;
			default:
				break;
		}
	} catch (exc) {
		console.error(exc.stack);
	}
};

_dss_editor._operation.handleMouseDown = function(eventObj) {
	this.viewerOPLast(eventObj);
};

_dss_editor._operation.handleMouseUp = function(eventObj) {
    
};

_dss_editor._operation.handleMouseMove = function(eventObj) {

};

_dss_editor._operation.handleMouseDBClick = function(eventObj) {

};

// 初始化Viewer
_dss_editor._operation.initViewer = function() {
	canvas.entity = $F("myCanvas");
	canvas.Event.init();
};

// 初始化消息
_dss_editor._operation.initMessage = function(msgModel, canvas) {
	try {
		var sysForView = this.completeSystemForView(msgModel, canvas);
		// 解析错误也不能初始化
		if (sysForView == null) {
			return false;
		}
		canvas.init(sysForView);
		// _dss_editor._model.system.initSys(canvas);
		// // 初始化system
		// initLinks(canvas);
		// 初始化连线
		if (canvas.sys == null || canvas.links == null) {
			return false;
		}
	} catch (e) {
		console.error(e.stack);
	} finally {
		_completeMsg = "";
	}
	return true;
};

_dss_editor._operation.completeSystemForView = function(msg, canvas) {
	if (msg.hasOwnProperty(PRESENTERNAME)) {
		canvas.presenterName = msg.presenterName;
	}
	if (msg.hasOwnProperty(MSG_TYPE)) {
		var type = msg.msgType;
		var sysForView = {};
		if (type.hasOwnProperty(MSG_VIEW_UIO)) {
			sysForView = type.viewUio;
		} else if (type.hasOwnProperty(MSG_VIEW)) {
			sysForView = this.completeView(type, canvas);
		} else if (type.hasOwnProperty(MSG_ACTIVATE)) {
			sysForView = this.completeActiveView(type, canvas);
		} else if (type.hasOwnProperty(MSG_DEACTIVE)) {
			sysForView = this.completeDeactiveView(type.deactivate, canvas);
		} else if (type.hasOwnProperty(MSG_IN)) {
			// sysForView = type.inMsg;
		}

		if (sysForView.hasOwnProperty(SYS_CHANGE)) {
			sysForView = this.modifySysForView(sysForView, canvas);
		}
		return sysForView;
	}
	return null;
};

/**
 * 如果类型是view，则sysForView的结构应该是里面为一个sys的内容 然后将这个内容进行转换
 *
 * @param type
 * @param canvas
 * @returns
 */
_dss_editor._operation.completeView = function(type, canvas) {
	// var viewSys = type.view.sys[0];
	// var content = null;
	// if (viewSys) {
	// if (viewSys.hasOwnProperty('content')
	// && viewSys.content.hasOwnProperty('simple')) {
	// content = viewSys.content.simple;
	// }
	// if (content) {
	// return JSON.parse(content);
	// }
	// }
	// return null;
	return type.view;
};

_dss_editor._operation.completeActiveView = function(type, canvas) {
	var sysForView = canvas.sysForView;
	var that = this;
	if (canvas.sys == null) {
		return null;
	}
	var diagram = type.activate;
	_dss_editor._model.system.initSystem(diagram);
	var fullName = diagram.getLogicFullName();
	var exitSys = _dss_editor._toolkit.findSystemByLogicName(canvas.sys.getChildren(), fullName);
	if (exitSys != null) {//已经有同名的，则转换成数组
		that.completeActiveArray(exitSys, diagram);
	} else {
		that.completeActiveSys(fullName, diagram, canvas);
	}
	if (diagram.content && diagram.content.simple && diagram.content.simple.sysForView) {
		that.completeActiveSysForView(diagram);
	}
	return sysForView;
};

_dss_editor._operation.completeActiveArray = function(exitSys, diagram) {
	var array = null;
	if (exitSys.style == ARRAY) {
		array = exitSys;
	} else if (ArrayTool.isArrayInstance(exitSys)) {
		array = exitSys.parent;
	} else {
		ArrayTool.convertSys2Array(exitSys, 1);
		array = exitSys.parent;
	}
	if (array != null) {
		diagram.setVisible(NO);
		array.addInstance(diagram);
		diagram.parent = array;
	}
	array.fullName = diagram.fullName;
};

_dss_editor._operation.completeActiveSys = function(fullName, diagram, canvas) {
	var index = fullName.lastIndexOf(".");
	if (index == -1) {
		canvas.sys.addChild(diagram);
	} else {
		var parentName = fullName.substring(0, index);
		var parent = _dss_editor._toolkit.findSystemByLogicName(canvas.sys.getChildren(), parentName);
		if (parent == null) {
			canvas.sys.addChild(diagram);
		} else {
			for (var i = 0; i < _dss_editor._toolkit.getSystemAllSubs(canvas.sys).length; i++) {
				var child = _dss_editor._toolkit.getSystemAllSubs(canvas.sys)[i];
				var fn = child.getLogicFullName();
				var pn = fn.substring(0, fn.lastIndexOf("."));
				if (pn.indexOf(fullName) == 0) {
					diagram.addChild(child);
					if (child.style == SYSTEM) {
						child.showInfo.rectangle.x -= diagram.getRectangle().x;
						child.showInfo.rectangle.y -= diagram.getRectangle().y;
					} else if(child.style == ARRAY){						
						child.subInstance[0].showInfo.rectangle.x -= diagram.getRectangle().x;
						child.subInstance[0].showInfo.rectangle.y -= diagram.getRectangle().y;
					}
					i--;
				}
			}
			parent.addChild(diagram);
		}
	}
};

_dss_editor._operation.completeActiveSysForView = function(diagram) {
	var text = diagram.name;
	if (text.substring(text.length - 2, text.length) == '_s' || text.substring(text.length - 2, text.length) == '_r') {
		text = text.substring(0, text.length - 2);
	}
	var viewCanvas = _dss_editor._canvas._operation.buildTab(text, _dss_editor._canvas._type.VIEWER);
	var viewSysForView = {
		complete : {
			sys : {},
			links : []
		}
	};
	if (diagram.content.simple.sysForView.hasOwnProperty('complete')) {
		if (diagram.content.simple.sysForView.complete.hasOwnProperty('sys')) {
			viewSysForView.complete.sys = diagram.content.simple.sysForView.complete.sys;
		}
		if (diagram.content.simple.sysForView.complete.hasOwnProperty('links')) {
			viewSysForView.complete.links = diagram.content.simple.sysForView.complete.links;
		}
	}
	// 初始化system
	viewCanvas.init(viewSysForView);
	viewCanvas.layout();
	viewCanvas.update();
};

/**
 * 仅仅UIO
 *
 * @param name
 * @param canvas
 * @returns
 */
_dss_editor._operation.completeDeactiveView = function(name, canvas) {
	if (canvas.sys == null) {
		return null;
	}
	var diagram = _dss_editor._toolkit.findSystemByLogicName(canvas.sys.getChildren(), name);
	if (diagram != null) {
		if (diagram.getSystemComplexity() > 1) {
			for (var i in diagram.getChildren()) {
				var child = diagram.getChildren()[i];
				if (!child) {
					continue;
				}
				if (child.style == SYSTEM) {
					if (child.getDeriveFlag() == RECEIVER) {
						if (diagram.hasOwnProperty('parent')) {
							diagram.parent.addChild(child);
						} else {
							canvas.sys.addChild(child);
						}
						child.showInfo.rectangle.x += diagram.getRectangle().x;
						child.showInfo.rectangle.y += diagram.getRectangle().y;
					}
				} else if (child.style == ARRAY) {
					var ins = child.subInstance[0];
					if (ins.getDeriveFlag() == RECEIVER) {
						if (diagram.hasOwnProperty('parent')) {
							diagram.parent.addChild(child);
						} else {
							canvas.sys.addChild(child);
						}
						ins.showInfo.rectangle.x += diagram.getRectangle().x;
						ins.showInfo.rectangle.y += diagram.getRectangle().y;
					}
				}

			}
		}
		if (canvas.getCurrentDrillSystem() != null) {
			canvas.drillUp();
		}
		var parent = null;
		if (diagram.hasOwnProperty('parent')) {
			parent = diagram.parent;
		} else {
			parent = canvas.sys;
			//.removeChild(diagram);
		}
		var cmd = new RemoveCommand(canvas, parent, diagram);
		cmd.doCommand();
		canvas.removeSelectionSystem();
		//diagram.clearHandles();
	}
	// diagram.getParent().removeChild(diagram);
	return canvas.sysForView;
};

// 修改当前viewer的图元信息
_dss_editor._operation.modifySysForView = function(changeView, canvas) {
	if (canvas.sys != null) {
		this.modifySys(changeView, canvas);
	}
	if (canvas.links != null) {
		this.modifyLinks(changeView, canvas);
	}
};

_dss_editor._operation.modifySys = function(changeView, canvas) {
	if (changeView.hasOwnProperty('node')) {
		var nodes = changeView.node;
		var parentName = '';
		var parent = {};
		for (var i = 0; i < nodes.length; i++) {
			var node = nodes[i];
			parentName = node.base;
			parent = _dss_editor._toolkit.findSystemByName(canvas.sys, parentName);
			if (parent == null) {
				continue;
			}
			if (node.hasOwnProperty('newNode')) {
				for (var j = 0; j < node.newNode.length; j++) {
					parent.addChild(node.newNode[j]);
				}
			}
			if (node.hasOwnProperty('modifedNode')) {
				for (var j = 0; j < node.modifedNode.length; j++) {
					var modiNode = node.modifedNode[j];
					if (parent.content.hasOwnProperty(COMPOSITE)) {
						for (var k = 0; k < parent.content.composite.subSys.length; k++) {
							var sub = parent.content.composite.subSys[k];
							if (modiNode.name == sub.name) {
								// removeChild(parent,sub);
								// addChild(parent,modiNode);
								parent.removeChild(sub);
								parent.addChild(modiNode);
								break;
							}
						}
					}
				}
			}
			if (node.hasOwnProperty('removedNode')) {
				for (var j = 0; j < node.removedNode.length; j++) {
					// removeChild(parent,node.newNode[j]);
					parent.removeChild(node.newNode[j]);
				}
			}
		}
	}
};

_dss_editor._operation.modifyLinks = function(changeView) {

};

// ------------------------------
_dss_editor._operation.connectServer = function(url) {
	var that = this;
	try {
		// var url = "ws://192.168.1.48:8080/pp";
		// var url = "ws://127.0.0.1:8080/system";
		if (_dss_editor.ws.hasOwnProperty('closed') && _dss_editor.ws.closed) {
		}
		_dss_editor.ws = new WebSocket(url);
		_dss_editor.ws.onopen = function() {

		};
		_dss_editor.ws.onmessage = function(message) {
			that.receiveMSG(message);
		};
		_dss_editor.ws.onclose = function() {
			//alert("socket已经关闭,请重新连接！");
			//_dss_editor.ws.closed = true;
			//connectServer(url);
		};

	} catch (exc) {
		console.error(exc.stack);
	}
};

_dss_editor._operation.receiveMSG = function(message) {
	if (!_dss_editor._toolkit.isMsgComplete(message.data)) {
		return;
	}
	console.log(_completeMsg);
	var msgModel = JSON.parse(_completeMsg);
	var canvas = {};
	if (msgModel.hasOwnProperty(PRESENTERNAME)) {
		var presenter = msgModel.presenterName;
		if (_dss_editor.canvas[presenter] != null) {
			canvas = _dss_editor.canvas[presenter];
			_dss_editor.activeCanvas = canvas;
			if (this.isCmdMSG(msgModel, canvas)) {
				canvas = this.receiveCmdMSG(msgModel, presenter);
			}
		} else {
			var canvasType = '';
			if (msgModel.msgType.hasOwnProperty('viewUio')) {
				canvasType = _dss_editor._canvas._type.VIEWUIO;//_dss_editor._canvas._type.VIEWUIO;
			} else if (msgModel.msgType.hasOwnProperty('view')) {
				canvasType = _dss_editor._canvas._type.VIEW;
			}
			//canvas = buildWindow(presenter, canvasType);
			canvas = _dss_editor._canvas._operation.buildTab(presenter,canvasType);
		}
	} else {
		return;
	}

	if (this.initMessage(msgModel, canvas)) {
		canvas.layout();
		canvas.update();
	}
};

/**
 * @param msgModel
 *            是通过JSON直接转换过来的模型
 * @returns {Boolean}
 */
_dss_editor._operation.isCmdMSG = function(msgModel, canvas) {
	if (canvas.type == _dss_editor._canvas._type.VIEW || canvas.type == _dss_editor._canvas._type.VIEWER) {
		var name = "";
		if (msgModel.msgType.hasOwnProperty('activate')) {
			name = msgModel.msgType.activate.complete.sys[0].name;
			if (name != 'display_r') {
				return true;
			}
		} else if (msgModel.msgType.hasOwnProperty('deactive')) {
			if (canvas.type == _dss_editor._canvas._type.VIEW || canvas.type == _dss_editor._canvas._type.VIEWER) {
				return true;
			}
		}
	}
	return false;
};

_dss_editor._operation.receiveCmdMSG = function(msgModel, presenter) {
	var cmdCanvas = _dss_editor.canvas[_dss_editor._canvas._type.COMMAND];
	var canvas = _dss_editor.canvas[presenter];
	if (msgModel.msgType.hasOwnProperty('activate')) {
		var system = msgModel.msgType.activate.complete.sys[0];
		// initDiagram(system);
		canvas.commands.push(system);
	} else if (msgModel.msgType.hasOwnProperty('deactive')) {
		for (var i = 0; i < canvas.commands.length; i++) {
			if (canvas.commands[i].getLogicFullName() == msgModel.msgType.deactive) {
				canvas.commands.splice(i, 1);
				break;
			}
		}
	}
	return cmdCanvas;
};

// Viewer操作.ALL
_dss_editor._operation.viewerOPLast = function(eventObj) {
	if (eventObj.canvas.hasOwnProperty('input')) {
		eventObj.canvas.input.commite();
		delete eventObj.canvas.input;
	}
};

_dss_editor._operation.openFile = function() {
	var handler = function() {
		localStorage.setItem('host', $F('ip').value);
		var url = "ws://" + $F('ip').value + ":8080/pp";
		this.connectServer(url);
		$('#dd').dialog('destroy');
	};
	var host = localStorage.getItem('host');
	if (!host) {
		host = 'localhost';
	}

	var dialog = new DscDialog('dd', 'Connect Server', "<input id='ip' style='width:280px;padding:1px' value=" + host + " />", handler);
	dialog.show();
};

_dss_editor._operation.newFile = function() {
	var handler = function() {
		var presenterName = $F('fileName').value;
		if (!localStorage.getItem(presenterName)) {
			// var canvas = buildWindow(presenterName,_dss_editor._canvas._type.VIEW);
			var canvas = _dss_editor._canvas._operation.buildTab(presenterName);
			var sysForView = {
				complete : {
					sys : {},
					links : []
				}
			};
			canvas.init(sysForView);
			// _dss_editor._model.system.initSys(canvas);
			// initLinks(canvas);
			localSave(presenterName, stringifyToLocalSaveMessage(canvas));
			addFile(presenterName);
			$('#ds').dialog('destroy');
		} else {
			alert('重名了请重新输入！');
		}
	};
	var dialog = new DscDialog('ds', 'Input name', "<input id='fileName' style='width:280px;padding:1px' value='' />", handler);
	dialog.show();
};

